<template>
	<div class="add_edit">
		<use-box>
			<el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
				<el-form-item label="拼团人数" prop="group_num" ref="group_num">
					<el-input type="number" v-model.number="form.group_num" :min="1" placeholder="请输入拼团人数" clearable
						oninput="value = parseInt(value)">
					</el-input>
				</el-form-item>
				<el-form-item label="成团人数" prop="group_success_num" ref="group_success_num">
					<el-input type="number" v-model.number="form.group_success_num" :min="1" placeholder="请输入成团人数"
						clearable oninput="value = parseInt(value)"></el-input>
					<div v-if="form.group_success_num && form.group_success_num <= form.group_num" class="remark_txt">
						参团人数达到{{ form.group_success_num }}代表拼团成功</div>
				</el-form-item>
				<!-- <el-form-item v-if="tableSkuData.length <= 0" label="原价">
					<el-input disabled :value="form.goods_obj && form.goods_obj.price || 0">
					</el-input>
				</el-form-item> -->
				<el-form-item v-if="tableSkuData.length <= 0" label="拼团价格" prop="goods_price" ref="goods_price">
					<el-input type="number" v-model.number="form.goods_price" :min="1" placeholder="请输入拼团价格" clearable>
					</el-input>
				</el-form-item>
				<!-- <el-form-item v-if="tableSkuData.length <= 0" label="原库存">
					<el-input disabled :value="form.goods_obj && form.goods_obj.stock_num || 0">
					</el-input>
				</el-form-item> -->
				<!-- <el-form-item v-if="tableSkuData.length <= 0" label="拼团库存" prop="group_stock_num" ref="group_stock_num">
					<el-input type="number" v-model.number="form.group_stock_num" :min="1" placeholder="请输入拼团库存"
						clearable>
					</el-input>
				</el-form-item> -->
				<!-- <el-form-item v-if="tableSkuData.length <= 0" label="占用原库存">
					<el-switch v-model="form.is_stock_num" active-color="#ff6a6c" inactive-color="#bbb"
						:active-value="1" :inactive-value="0"></el-switch>
				</el-form-item> -->
				<el-form-item label="活动时间" prop="activityTime" ref="activityTime">
					<el-date-picker v-model="form.activityTime" type="datetimerange" align="right" range-separator="至"
						start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerTimeOptions"
						class="time">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="参团有效期" prop="group_time" ref="group_time">
					<el-input type="number" v-model.number="form.group_time" :min="0" placeholder="请输入参团有效期" clearable
						oninput="value = parseInt(value)">
					</el-input>
					<div class="remark_txt">单位小时</div>
				</el-form-item>
				<el-form-item label="排序">
					<el-input type="number" v-model.number="form.sort" :min="1" placeholder="请输入排序" clearable
						oninput="value = parseInt(value) || 1">
					</el-input>
				</el-form-item>
				<el-form-item label="备注">
					<el-input v-model="form.remark" placeholder="请输入备注" clearable></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-switch v-model="form.state" active-color="#ff6a6c" inactive-color="#bbb" active-value="启用"
						inactive-value="禁用"></el-switch>
				</el-form-item>
				<el-form-item label="拼团商品" prop="goods_obj" ref="goods_obj">
					<el-button v-if="!form.goods_obj" round icon="el-icon-plus" class="addGoods-btn" @click="addGoods">
					</el-button>
					<el-button v-else round icon="iconfont iconbianji" class="addGoods-btn" @click="addGoods">
					</el-button>
				</el-form-item>
				<el-form-item v-if="form.goods_obj">
					<div class="dflex_wrap">
						<el-card :body-style="{ padding: '0px' }" shadow="hover"
							class="card margin_b_10 padding_10 padding_t_20 pos_r margin_r_15 crpr">
							<use-carousel :width="150" :height="150" :imgs="form.goods_obj.imgs"
								:video="form.goods_obj.video"></use-carousel>
							<div class="card_bottom pos_a">
								<el-popover :open-delay="350" :close-delay="80" placement="top" trigger="hover"
									:content="form.goods_obj.name">
									<div slot="reference" class="name pos_a ellipsis crpr padding_lr_10 sele_none">
										{{ form.goods_obj.name }}
									</div>
								</el-popover>
								<div class="price pos_a sele_none">{{ form.goods_obj.price / 100 }}</div>
								<div class="m_price pos_a sele_none">{{ form.goods_obj.market_price / 100 }}</div>
							</div>
							<div class="el-icon-close crpr pos_a" @click="goodsRemove"></div>
						</el-card>
					</div>
				</el-form-item>
				<div v-if="tableSkuData.length > 0">
					<el-form-item label-width="0">
						<el-table :data="tableSkuData" border>
							<el-table-column label="图片" align="center" width="120" :resizable="false" fixed="left">
								<template slot-scope="scope">
									<el-image style="width: 70px;height: 70px;padding: 1px;box-sizing: content-box;"
										:src="scope.row.img" :preview-src-list="scope.row.previewImgs" fit="cover">
									</el-image>
								</template>
							</el-table-column>
							<el-table-column align="center" min-width="260">
								<template slot="header" slot-scope="scope">
									<div>拼团价</div>
									<div class="dflex_level_c margin_t_10">
										<el-input class="batchInput margin_r_10" size="medium" type="number" :min="1"
											v-model="batchGroupPrice" placeholder="拼团价" clearable></el-input>
										<el-button class="batchBtn" size="medium" @click="batchEdit('goods_price')">
											修改
										</el-button>
									</div>
								</template>
								<template slot-scope="scope">
									<el-input style="width:100%" type="number" :min="1"
										v-model.number="scope.row.goods_price"
										@change="tableInputEdit('goods_price', scope.row, '拼团价')" placeholder="拼团价">
									</el-input>
									<div class="remark_txt margin_t_0 left_just">单位分，{{ scope.row.goods_price || 0 }}
										分 =
										{{ scope.row.goods_price / 100 || 0 }} 元
									</div>
								</template>
							</el-table-column>
							<el-table-column align="center" min-width="260">
								<template slot="header" slot-scope="scope">
									<div>拼团库存</div>
									<div class="dflex_c">
										<div class="lh_1 margin_r_5">占用原库存</div>
										<el-switch v-model="form.is_stock_num" active-color="#ff6a6c"
											inactive-color="#bbb" :active-value="1" :inactive-value="0"
											@change="isStockNumChange"></el-switch>
									</div>
									<div class="dflex_level_c margin_t_10">
										<el-input class="batchInput margin_r_10" size="medium" type="number" :min="1"
											v-model="batchGroupStockNum" placeholder="拼团库存" clearable></el-input>
										<el-button class="batchBtn" size="medium" @click="batchEdit('group_stock_num')">
											修改
										</el-button>
									</div>
								</template>
								<template slot-scope="scope">
									<el-input style="width:100%" type="number"
										v-model.number="scope.row.group_stock_num" :min="1"
										@change="tableInputEdit('group_stock_num', scope.row, '库存')" placeholder="库存">
									</el-input>
									<div class="remark_txt margin_t_0 left_just">SKU库存数</div>
								</template>
							</el-table-column>
							<el-table-column label="原价" align="center" min-width="260">
								<template slot-scope="scope">
									<el-input style="width:100%" type="number" v-model.number="scope.row.price"
										disabled></el-input>
									<div class="remark_txt margin_t_0 left_just">单位分，{{ scope.row.price || 0 }}
										分 = {{ scope.row.price / 100 || 0 }} 元
									</div>
								</template>
							</el-table-column>
							<el-table-column label="原库存" align="center" min-width="260">
								<template slot-scope="scope">
									<el-input style="width:100%" type="number" v-model.number="scope.row.stock_num"
										disabled>
									</el-input>
									<div class="remark_txt margin_t_0 left_just">SKU原库存数</div>
								</template>
							</el-table-column>
							<el-table-column :label="item.name" align="center"
								v-for="(item, i) in skuDatas.filter(x => x.name.trim() && x.enable)" :key="i"
								min-width="200">
								<template slot-scope="scope">
									<div>{{scope.row[`sku${i + 1}_spec`]}}</div>
								</template>
							</el-table-column>
						</el-table>
					</el-form-item>
				</div>
				<el-form-item>
					<use-affix position="bottom" :offset="58">
						<el-button :loading="formLoading" round icon="el-icon-check" class="confirm-btn"
							@click="submitForm('ruleForm')">提交</el-button>
						<el-button round icon="el-icon-back" class="return-btn" @click="returnPage">返回</el-button>
					</use-affix>
				</el-form-item>
			</el-form>
		</use-box>
		<goods ref="goodsRef" @choiceGoods="getGoodsDatas"></goods>
	</div>
</template>

<script>
	const __name = 'wmzmall-market-groupbuy';
	const __goodsSku = 'wmzmall-goods-sku';
	export default {
		data() {
			const validateGroupNum = async (rule, value, callback) => {
				if (!value) {
					return callback(new Error('请输入拼团人数'));
				}

				if (value < 2) {
					return callback(new Error('拼团人数不能小于2'));
				}

				if (this.form.group_success_num) {
					this.$refs.ruleForm.validateField('group_success_num');
				}

				callback();
			};
			const validateGroupSuccessNum = async (rule, value, callback) => {
				if (!value) {
					return callback(new Error('请输入成团人数'));
				}

				if (value > this.form.group_num) {
					return callback(new Error('成团人数不能大于拼团人数'));
				}

				callback();
			};
			const validateGroupPrice = async (rule, value, callback) => {
				if (!value) {
					return callback(new Error('请输入拼团价格'));
				}

				callback();
			};
			const validateGroupStockNum = async (rule, value, callback) => {
				if (!value) {
					return callback(new Error('请输入拼团库存'));
				}

				callback();
			};
			const validateGroupTime = async (rule, value, callback) => {
				if (!value) {
					return callback(new Error('请输入参团有效期'));
				}

				callback();
			};
			const validateGoodsObj = async (rule, value, callback) => {
				if (!value) {
					return callback(new Error('请选择拼团商品'));
				}

				callback();
			};
			return {
				dataId: '',
				formLoading: false,
				form: {
					group_num: '',
					group_success_num: '',
					goods_price: '',
					is_stock_num: 0,
					group_stock_num: '',
					activityTime: [],
					group_begin_time: '',
					group_end_time: '',
					group_time: '',
					sort: 0,
					remark: '',
					state: '启用',
					goods_id: '',
					goods_obj: null,
					group_members: [],
					group_member_cnt: 0,
					group_order_cnt: 0
				},
				pickerTimeOptions: {
					disabledDate(time) {
						return time.getTime() < Date.now() - 3600 * 1000 * 24;
					},
					shortcuts: [{
							text: '最近一周',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
								picker.$emit('pick', [end, start]);
							}
						},
						{
							text: '最近一个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
								picker.$emit('pick', [end, start]);
							}
						},
						{
							text: '最近三个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
								picker.$emit('pick', [end, start]);
							}
						}
					]
				},
				rules: {
					group_num: [{
						required: true,
						validator: validateGroupNum,
						trigger: 'change'
					}],
					group_success_num: [{
						required: true,
						validator: validateGroupSuccessNum,
						trigger: 'change'
					}],
					goods_price: [{
						required: true,
						validator: validateGroupPrice,
						trigger: 'change'
					}],
					group_stock_num: [{
						required: true,
						validator: validateGroupStockNum,
						trigger: 'change'
					}],
					activityTime: [{
						type: 'array',
						required: true,
						message: '请选择日期',
						trigger: 'change'
					}],
					group_time: [{
						required: true,
						validator: validateGroupTime,
						trigger: 'change'
					}],
					goods_obj: [{
						required: true,
						validator: validateGoodsObj,
						trigger: 'change'
					}]
				},
				skuDatas: [],
				tableSkuData: [],
				batchGroupPrice: null,
				batchGroupStockNum: null
			};
		},
		methods: {
			async loadData() {
				if (!this.dataId) {
					this.$db[__name].getsort().then(res => {
						if (res.code == 200) {
							this.form.sort = ++res.datas.sort;
						}
					});
					return;
				}

				await this.$db[__name].tofirst(this.dataId).then(res => {
					if (res.code == 200) {
						for (let item in this.form) {
							this.form[item] = res.datas[item];
						}

						this.form.activityTime = [];
						this.form.activityTime.push(res.datas.group_begin_time);
						this.form.activityTime.push(res.datas.group_end_time);
					}
				});
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid, obj) => {
					// 默认获取第一个未验证 form 属性名
					this.$api.set_unvalidated_form_focus(this, obj);
					if (valid) {
						this.formLoading = true;
						if (this.form.activityTime && this.form.activityTime.length > 0) {
							if (this.form.activityTime[0] == this.form.group_begin_time && this.form.activityTime[
									1] == this.form.group_end_time) {
								this.form.activityTime[0] = new Date(this.form.activityTime[0]);
								this.form.activityTime[1] = new Date(this.form.activityTime[1]);
							}
							this.form.group_begin_time = this.form.activityTime[0].getTime();
							this.form.group_end_time = this.form.activityTime[1].getTime();
						}

						delete this.form.activityTime;

						if (!this.dataId) {
							this.$db[__name].add(this.form).then(res => {
								if (res.code == 200) {
									this.getOpenerEventChannel().emit('loadData');
									this.returnPage();
								}
								this.formLoading = false;
							}).catch(() => {
								this.formLoading = false;
							})
						} else {
							this.$db[__name].update(this.dataId, this.form).then(res => {
								if (res.code == 200) {
									this.getOpenerEventChannel().emit('loadData');
									this.returnPage();
								}
								this.formLoading = false;
							}).catch(() => {
								this.formLoading = false;
							})
						}
					}
				});
			},
			addGoods() {
				this.$refs.goodsRef.show({
						_id: this.$db.$cmd.nin([this.form.goods_id]),
						state: '销售中'
					},
					true
				);
			},
			getGoodsDatas(datas) {
				// this.skuDatas = datas.skus;
				// this.$db[__goodsSku]
				// 	.where({
				// 		goods_id: datas._id
				// 	})
				// 	.tolist({
				// 		loading: false
				// 	}).then(res => {
				// 		if (res.code == 200) {
				// 			res.datas.forEach(x => {
				// 				x.previewImgs = [x.img];
				// 				x.goods_price = this.form.goods_price || x.price;

				// 				if (this.form.is_stock_num) {
				// 					if (this.form.group_stock_num >= x.stock_num) {
				// 						x.group_stock_num = x.stock_num;
				// 						x.stock_num -= x.stock_num;
				// 						return;
				// 					}
				// 					x.group_stock_num = this.form.group_stock_num;
				// 					x.stock_num -= this.form.group_stock_num;
				// 					return;
				// 				}

				// 				x.group_stock_num = this.form.group_stock_num || x.stock_num;
				// 			});
				// 			this.tableSkuData = res.datas;
				// 		}
				// 	})

				this.form.goods_obj = datas;
				this.form.goods_id = datas._id;
				this.$refs.goods_obj.clearValidate();
			},
			goodsRemove() {
				this.skuDatas = [];
				this.tableSkuData = [];
				this.form.goods_obj = null;
				this.form.goods_id = '';
				this.$refs.ruleForm.validateField('goods_obj');
			},
			batchEdit(res) {
				if (res == 'goods_price') {
					if (this.batchGroupPrice <= 0) {
						this.$message('请输入有效的拼团价');
						return;
					}
				} else if (res == 'group_stock_num') {
					if (!this.batchGroupStockNum) {
						this.$message('请输入有效的拼团库存');
						return;
					}
				}
				this.tableSkuData.forEach(x => {
					if (res == 'goods_price') {
						x.goods_price = this.batchGroupPrice;
					} else if (res == 'group_stock_num') {
						x.group_stock_num = this.batchGroupStockNum;
					}
				});
			},
			tableInputEdit(key, row, name) {
				if (['goods_price', 'stock_num'].includes(key)) {
					// 保存上一次的有效值
					let prev_val = event.target.dataset.val || 0;

					if (row[key] <= 0) {
						this.$message(`请输入有效的${name}`);
						row[key] = prev_val || 1;
						return;
					}

					event.target.dataset.val = row[key];
				}
			},
			isStockNumChange() {},
			returnPage() {
				uni.$emit('closeTab');
				uni.redirectTo({
					url: '/pages/marketing/groupbuy/limit_groupbuy'
				});
			}
		},
		created() {
			this.dataId = this.$route.query.id || '';
			this.loadData();
		}
	};
</script>

<style>
	.addGoods-btn:hover,
	.addGoods-btn:focus {
		color: #ff6a6c;
		border-color: #ff6a6c;
		background-color: #fff;
	}

	.card {
		border-radius: 10px;
		overflow: hidden;
	}

	.card .img {
		transition: transform 1s;
	}

	.card:hover .img {
		transform: scale(1.08);
	}

	.card .card_bottom {
		left: 0;
		right: 0;
		bottom: 0;
		color: #fff;
		width: 100%;
		height: 70px;
		text-align: center;
		background-color: rgba(0, 0, 0, 0.4);
		z-index: 999;
	}

	.card_bottom .name {
		top: 0;
		font-size: 16px;
	}

	.card_bottom .price {
		top: 20px;
		left: 50%;
		transform: translate(-50%, 0);
		color: #fff;
		font-size: 14px;
	}

	.card_bottom .m_price {
		top: 36px;
		left: 50%;
		transform: translate(-50%, 0);
		color: #fff;
		font-size: 14px;
	}

	.card .ellipsis {
		width: 100%;
	}

	.card .el-icon-close {
		right: 4px;
		top: 4px;
	}

	.card .el-icon-close:hover {
		color: #ff6a6c;
	}

	>>>.el-table__row:hover>td {
		background-color: #fff !important;
	}

	>>>.el-table__row--striped:hover>td {
		background-color: #fff !important;
	}

	.skuInput {
		width: 200px;
	}

	.sku_and_img {
		width: 120px;
		height: 120px;
		background-color: rgba(0, 0, 0, 0.1);
		padding: 10px;
		padding-bottom: 0px;
		border-radius: 10px;
	}

	.batchInput {
		height: 36px;
	}

	.batchInput>>>.el-input__inner {
		border-color: #dcdfe6;
		background-color: #fff;
	}

	.batchBtn:hover,
	.batchBtn:focus {
		color: #ff6a6c;
		border-color: #ff6a6c;
		background-color: #fff;
	}
</style>
